import React, { Fragment } from 'react'
import {
  View,
  StyleSheet,
  ScrollView,
  LayoutAnimation,
  DeviceEventEmitter,
  RefreshControl,
  Linking
} from 'react-native'
import { connect } from 'react-redux'
import BasePage from 'src/pageP/base/base-page/index'
import HomeHeader from './components/HomeHeader'
import HomeBannerC from 'src/components/banner-c/index'
import LiveList from 'src/components/live-list/LiveList'
import PartTitle from './components/PartTitle'
import LabelList from './components/LabelList'
import {
  homeFamousList,
  goodPostFamousList,
  homeChannelList,
  homeIndustryCategory
} from 'src/utils/RequestAPI'
import FamousSwiper, { FamousSwiperHeight } from './components/FamousSwiper'
import {
  ScaleS,
  STATUSBAR_HEIGHT,
  WIDTH,
  ScaleT,
  IS_ANDROID
} from 'src/utils/ScreenUtil'
import NavigationUtil from 'utils/NavigationUtil'
import BackHandlerUtil from 'src/utils/BackHandlerUtil'

const searchHeight = STATUSBAR_HEIGHT + ScaleS(20) + ScaleS(42)
const bannerHeight = ((WIDTH - ScaleS(40)) * 150) / 335 + 26 + ScaleS(15)
const mapActiontoProps = dispatch => ({})

@connect(
  ({ userinfo, im, landmark }) => ({
    userinfo,
    landmark,
    ...im
  }),
  mapActiontoProps
)
class CHomePage extends BasePage {
  constructor(props) {
    super(props)
    this.FamousSwiperHeightAdded = false
    this.moveAbleHeight = searchHeight + bannerHeight
    this.state = {
      dataArr: [],
      hideItem: false,
      scrollEnabled: true,
      pushMsg: '',
      famous: null,
      cardList: ['家教辅导', '活动策划', '产品推广', '校园推广'],
      liveData: [],
      isHeaderRefreshing: false // 头部是否正在刷新
    }
  }

  componentDidMount() {
    this._willBlurSubscription = this.props.navigation.addListener(
      'willBlur',
      payload => {
        if (IS_ANDROID) {
          BackHandlerUtil.removeHardwareBackPress(
            BackHandlerUtil.doublePressExitApp
          )
        }
      }
    )
    this.reLoadData(false)
  }

  componentDidFocus() {
    if (IS_ANDROID) {
      BackHandlerUtil.hardwareBackPressListener(
        BackHandlerUtil.doublePressExitApp
      )
    }
    this._homeChannelList()
  }

  componentWillUnmount() {
    super.componentWillUnmount()
    this._willBlurSubscription && this._willBlurSubscription.remove()
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.landmark.cityName !== this.props.landmark.cityName) {
      // props城市改变
      this.reLoadData(this.props.landmark.cityName)
    }
    if (prevProps.userinfo.userId !== this.props.userinfo.userId) {
      // props城市改变
      this.reLoadData(this.props.landmark.cityName)
    }
    // return null
  }

  _isPageB = () => {
    return this.pageType === 'B'
  }

  reLoadData = status => {
    const { isHeaderRefreshing } = this.state
    if (!isHeaderRefreshing) {
      status &&
        this.setState({
          isHeaderRefreshing: true
        })
      Promise.all([
        this._homeFamousList(),
        this._homeIndustryCategory()
      ]).finally(() => {
        status &&
          this.setState({
            isHeaderRefreshing: false
          })
      })
      this._homeChannelList()
    }
  }

  /**
   * 首页校招列表加载
   * @private
   */
  _homeChannelList = () => {
    return new Promise(resolve => {
      if (!this._isPageB()) {
        const {
          userinfo: { userId }
        } = this.props
        homeChannelList({ params: { userId, limit: 999 } }).then(data => {
          const { data: channel = [] } = data
          this.setState(
            {
              liveData: channel
            },
            () => {
              resolve()
            }
          )
        })
      }
    })
  }

  /**
   * 首页行业分类
   * @private
   */
  _homeIndustryCategory = () => {
    return new Promise(resolve => {
      if (!this._isPageB()) {
        const {
          userinfo: { userId },
          city
        } = this.props
        homeIndustryCategory({ params: { userId, city } }).then(data => {
          const { data: category = [] } = data
          this.setState(
            {
              cardList: category
            },
            () => {
              resolve()
            }
          )
        })
      }
    })
  }

  /**
   * 首页名企加载
   * @private
   */
  _homeFamousList = () => {
    return new Promise(resolve => {
      if (!this._isPageB()) {
        const { landmark: { cityName: city } = {} } = this.props
        goodPostFamousList({ params: { city } }).then(data => {
          console.info(data)
          const { data: famous = [] } = data
          // LayoutAnimation.easeInEaseOut()
          if (famous.length > 0) {
            // TODO
            if (!this.FamousSwiperHeightAdded) {
              this.moveAbleHeight = this.moveAbleHeight + FamousSwiperHeight
              this.FamousSwiperHeightAdded = true
            }
            this.setState(
              {
                famous: famous.map((e, index) => ({ ...e, index }))
              },
              () => {
                resolve()
              }
            )
          } else {
            if (this.FamousSwiperHeightAdded) {
              this.moveAbleHeight = this.moveAbleHeight - FamousSwiperHeight
              this.FamousSwiperHeightAdded = false
            }
            this.setState(
              {
                famous: null
              },
              () => {
                resolve()
              }
            )
          }
        })
      }
    })
  }

  goCheckAllJobs = () => {
    // 点击优选岗位查看全部
    NavigationUtil.navigate('FamousList')
  }

  _swiperClick = ({ item }) => {
    console.log(item)
    this.props.navigation.navigate('CommonWebView', {
      source: { uri: item.url }
    })
  }

  childRender() {
    const { famous, cardList, liveData, isHeaderRefreshing } = this.state
    const { landmark: { cityName } = {} } = this.props
    return (
      <Fragment>
        <HomeHeader
          cityName={cityName}
          cityClick={this.cityClick}
          searchClick={this._searchClick}
        />
        <ScrollView
          style={styles.container}
          // stickyHeaderIndices={[0]}
          showsVerticalScrollIndicator={false}
          refreshControl={
            <RefreshControl
              refreshing={isHeaderRefreshing}
              onRefresh={this.reLoadData}
            />
          }
        >
          <HomeBannerC cityName={this.props.landmark.cityName} swiperClick={this._swiperClick} />

          {famous && <PartTitle
            stylePart={styles.famousTitle}
            title={'优选名企'}
            rightTitle={'全部'}
            rightPress={this.goCheckAllJobs} />}
          {famous && <FamousSwiper swipers={famous} />}
          {famous && (
            <LabelList
              cardList={cardList}
              homeIndustryClick={this._homeIndustryClick}
            />
          )}

          <PartTitle
            stylePart={styles.liveTitle}
            title={'校招live'}
            rightTitle={'查看全部'}
          />
          <View style={styles.liveListContainer}>
            {liveData.map((item, index) => {
              return <LiveList key={item.id || index} liveData={item} />
            })}
          </View>
        </ScrollView>
      </Fragment>
    )
  }

  /**
   * 城市选择
   */
  cityClick = () => {
    const {
      landmark: { cityName }
    } = this.props
    NavigationUtil.navigate('CommonListCity', {
      cityName
    })
  }

  _homeIndustryClick = ({ category, type }) => {
    this._navigatePosition({
      category,
      type
    })
  }

  /***
   * 导航到职位Tab
   * @param params
   * @private
   */
  _navigatePosition = params => {
    const positionParams = {
      position: params
    }
    NavigationUtil.navigate('CPositionPage', positionParams)
    DeviceEventEmitter.emit('CPositionPage', positionParams)
  }

  _searchClick = () => {
    NavigationUtil.navigate('HomeSearch')
  }
}

export default CHomePage

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  famousTitle: {
    paddingTop: ScaleS(30)
  },
  liveTitle: {
    paddingTop: ScaleS(30),
    paddingBottom: ScaleS(0)
  },
  liveListContainer: {
    flexDirection: 'column',
    paddingHorizontal: ScaleS(20),
    paddingBottom: ScaleS(30)
  }
})
